package dth.bean;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Date;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;

import org.primefaces.event.FileUploadEvent;

import dth.dao.OrderSetupBoxDAO;
import dth.dao.PackageDAO;
import dth.dao.SetupBoxDAO;
import dth.entity.Account;
import dth.entity.OrderSetupBox;
import dth.entity.Package;
import dth.entity.SetupBox;
import dth.utils.DthUtil;

@ManagedBean(name="setupboxBean")
public class SetupBoxBean {
	@ManagedProperty(value = "#{loginBean}")
	private LoginBean loginBean;// get session login bean
	private int id;//use to insert delete
	private int id_order;
	private String type;
	private double price;
	private int fkAdminId;
	private String image;
	private String imageOld;
	private String des;
	private int quantity;
	private String destination = "//WebContent//images//";	
	private String fileName="";
	private String priceStr;
	
	
	public LoginBean getLoginBean() {
		return loginBean;
	}
	public void setLoginBean(LoginBean loginBean) {
		this.loginBean = loginBean;
	}
	public String getDestination() {
		return destination;
	}
	public void setDestination(String destination) {
		this.destination = destination;
	}
	public String getPriceStr() {
		return DthUtil.getFormatedNumber(price);
	}
	public void setPriceStr(String priceStr) {
		this.priceStr = priceStr;
	}
	public String getImageOld() {
		return imageOld;
	}
	public void setImageOld(String imageOld) {
		this.imageOld = imageOld;
	}
	public String getFileName() {
		return fileName;
	}
	public void setFileName(String fileName) {
		this.fileName = fileName;
	}
	private List<SetupBox> filteredSetupBox;
	
	public List<SetupBox> getFilteredSetupBox() {
		return filteredSetupBox;
	}
	public void setFilteredSetupBox(List<SetupBox> filteredSetupBox) {
		this.filteredSetupBox = filteredSetupBox;
	}
	public int getId_order() {
		return id_order;
	}
	public void setId_order(int id_order) {
		this.id_order = id_order;
	}
	public int getQuantity() {
		return quantity;
	}
	public void setQuantity(int quantity) {
		this.quantity = quantity;
	}
	public String getDes() {
		return des;
	}
	public void setDes(String des) {
		this.des = des;
	}
	public String getImage() {
		return image;
	}
	public void setImage(String image) {
		this.image = image;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}
	public double getPrice() {
		return price;
	}
	public void setPrice(double price) {
		this.price = price;
	}
	public int getFkAdminId() {
		return fkAdminId;
	}
	public void setFkAdminId(int fkAdminId) {
		this.fkAdminId = fkAdminId;
	}
	public SetupBoxBean() {
		// TODO Auto-generated constructor stub
		
		System.out.println("---request url:"+DthUtil.getRequestURL());
		if(DthUtil.getRequestURL().contains("setupbox.xhtml")){
			System.out.println("--vao day role:"+LoginBean.roleCode);
			if(LoginBean.roleCode!=1)
				DthUtil.navigateTo("welcome.xhtml");
		}
		
		System.out.println("--SetupBoxBean");
		Object objectAction=DthUtil.getRequest().getParameter("action");
		String ob = DthUtil.getRequest().getParameter("action");
		System.out.println("----------action:"+objectAction);
		String filename = DthUtil.getRequest().getParameter("filename");
		if(filename!=null)
		{
			this.image = filename;
		}
		if(objectAction!=null)
		{
			if(objectAction.equals("insert"))
			{
				String image = DthUtil.getRequest().getParameter("imageI");
				this.fileName = image; 
			}
			if(objectAction.equals("delete"))
			{
				Object objectId=DthUtil.getRequest().getParameter("setupbox_id");
				String image = DthUtil.getRequest().getParameter("setupbox_image");
				this.image = image;
				if(objectId!=null)
					id=Integer.parseInt(objectId.toString());
				System.out.println("setupbox id ==================================== " + id);
			}
			else if(objectAction.equals("update"))
			{
				Object objectId=DthUtil.getRequest().getParameter("setupbox_id");
				if(objectId!=null)
					id=Integer.parseInt(objectId.toString());
				System.out.println("---id edit:"+id);
				for(SetupBox setup:getListSetupBox())
				{
					if(setup.getId()==id)
					{
						this.type =setup.getType();
						this.price=setup.getPrice();
						this.fkAdminId=setup.getFkAdminId();
						this.image = setup.getImage();
						this.des = setup.getDescription();
						this.fileName = image;
						this.imageOld = image;
					}
				}
			
			}
		}
	}
	public java.util.List<SetupBox> getListSetupBox()
	{
		System.out.println("get all list setupbox");
		SetupBoxDAO  setupboxDAO=new SetupBoxDAO();
		return setupboxDAO.getListSetupBox();
	}
	public void delete()
	{
		SetupBoxDAO  setupboxDAO=new SetupBoxDAO();
		int count=setupboxDAO.delete(id);
		if(count>0)
			DthUtil.showMessage("Thông báo", "Xóa thành công");
		else
			DthUtil.showMessage("Thông báo", "Xóa thất bại");
		System.out.println("immmmmmmmmmmmmmgggggggggggggggggg " +image);
		delImg(image);
	}
	public void insert()
	{
			System.out.println("iimmmmmmmmmmmmmm" + imageOld);
			System.out.println("---id="+id);
			String filename = DthUtil.getRequest().getParameter("filename");
			SetupBoxDAO  setupboxDAO=new SetupBoxDAO();
			SetupBox setup=new SetupBox();
			setup.setId(id);
			setup.setType(type);
			setup.setPrice(price);
			Account ac = DthUtil.getAccountDTH();
			
			setup.setFkAdminId(ac.getFkAdminId());//set cung
			
//			Account ac = DthUtil.getAccountDTH();
//			setup.setFkAdminId(ac.getFkAdminId());
			
			setup.setImage(filename); 
			setup.setDescription(des);
			System.out.println("img"+setup.getImage());
			java.util.Date date=new java.util.Date();//lay ngay hien tai
			setup.setDateInsert(new Date(date.getTime()));
			int count=0;
			if(id==0)
			{
				
				count=setupboxDAO.insert(setup);
				if(count==1)
				{
					System.out.println("insert thành công");
					DthUtil.showMessage("Thông báo", "insert thành công");
				}
				if(count == 2)
				{
					System.out.println("Bạn chưa nhập giá");
					DthUtil.showMessage("Thông báo", "Giá phải > 0");
				}
				if(count == 3)
				{
					System.out.println("Bạn chưa nhập Type");
					DthUtil.showMessage("Thông báo", "Bạn chưa nhập Type ");
				}
				if(count == 4)
				{
					System.out.println("Bạn chưa nhập Type và giá");
					DthUtil.showMessage("Thông báo", "Bạn chưa nhập Type và giá phải > 0");
				}
				if(count == 6)
				{
					System.out.println("Bạn chưa chọn hình");
					DthUtil.showMessage("Thông báo", "Bạn chưa chọn hình");
				}
				if(count <=0)
				{
					System.out.println("Insert that bai");
					DthUtil.showMessage("Thông báo", "Insert that bai");
				}
				if(count==5)
				{
					System.out.println("Insert that bai");
					DthUtil.showMessage("Thông báo", "đã có type: '"+type+"' trong csdl");
				}
				
					
			}
			else
			{
				System.out.println("setupboxBean update: type= " + type
						+ " img= " + filename + "des= " + des+ " id: "+id);
				count=setupboxDAO.update(setup);
				if(count==1)
				{
					if(!imageOld.equals(filename))
					{
						delImg(imageOld);
					}
					System.out.println("Update thành công");
					DthUtil.showMessage("Thông báo", "Update thành công");
				}
				if(count == 2)
				{
					System.out.println("Bạn chưa nhập Giá ");
					DthUtil.showMessage("Thông báo", "Giá phải > 0");
				}
				if(count == 3)
				{
					System.out.println("Bạn chưa nhập Type ");
					DthUtil.showMessage("Thông báo", "Bạn chưa nhập Type ");
				}
				if(count == 4)
				{
					System.out.println("Bạn chưa nhập Type và giá");
					DthUtil.showMessage("Thông báo", "Bạn chưa nhập Type và giá phải > 0");
				}
				if(count == 6)
				{
					System.out.println("Bạn chưa chọn hình");
					DthUtil.showMessage("Thông báo", "Bạn chưa chọn hình");
				}
				if(count <=0)
				{
					System.out.println("Update that bai");
					DthUtil.showMessage("Thông báo", "Update that bai");
				}
				
			}
	}
	
	public void insertOrder()
	{
		OrderSetupBox order = new OrderSetupBox();
		OrderSetupBoxDAO dao = new OrderSetupBoxDAO();
		
		
		java.util.Date date=new java.util.Date();//lay ngay hien tai
		order.setDateInsert(new Date(date.getTime()));
		order.setId(0);
		order.setFkDealerId(1);
		order.setFkDistributorId(0);// set cung', la` do distribu dat. hang`
		System.out.println("iddddddddddddddddddddddddddddddddddddddddddddddd  "+ id);
		order.setFkSetupBox(id);
		order.setFkUserId(0);
		order.setQuantity(quantity);
		order.setStatus(0); // chua thanh toan
		int count = 0;
		count=dao.insert(order);
		if(count >0)
			DthUtil.showMessage("Thông báo", "Đặt hàng thành công");
		else
			DthUtil.showMessage("Thông báo", "Đặt hàng thất bại");
		
	}
	
	public void upload(FileUploadEvent event) {
		// Do what you want with the file
		ExternalContext extContext = FacesContext.getCurrentInstance().getExternalContext();
		try {
			this.image = event.getFile().getFileName();
			copyFile(event.getFile().getFileName(), event.getFile()
					.getInputstream());
			FacesMessage msg = new FacesMessage("Success! ", event.getFile()
					.getFileName() + " is uploaded.");
			FacesContext.getCurrentInstance().addMessage(null, msg);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public void copyFile(String fileName, InputStream in) {
		try {

			// write the inputStream to a FileOutputStream
			
			
			ExternalContext extContext = FacesContext.getCurrentInstance().getExternalContext();
			OutputStream out = new FileOutputStream(new File(extContext.getRealPath("//images//" +fileName)));
			this.fileName = fileName;
			System.out.println(extContext.getRealPath("//images//" ));
			
//			OutputStream out = new FileOutputStream(new File(destination
//					+ fileName));
			int read = 0;
			byte[] bytes = new byte[1024];

			while ((read = in.read(bytes)) != -1) {
				out.write(bytes, 0, read);
			}
			in.close();
			out.flush();
			out.close();

			System.out.println("New file created!");
		} catch (IOException e) {
			System.out.println(e.getMessage());
		}
	}
	public void delImg(String name) {
		
		System.out.println("deleteeeeeeeeeee0 " +name);
		ExternalContext extContext = FacesContext.getCurrentInstance().getExternalContext();
		File deleteFile = new File(extContext.getRealPath("//images//" + name)); 
		deleteFile.delete();
	}
	public void delImg1() {
		for(SetupBox setup:getListSetupBox())
		{
			if(setup.getId()==id)
			{
				if(!image.trim().equals(setup.getImage().trim()))
				{
					System.out.println("deleteeeeeeeeeee1 " +image + "id "+id);
					ExternalContext extContext = FacesContext.getCurrentInstance().getExternalContext();
					File deleteFile = new File(extContext.getRealPath("//images//" + image)); 
			        deleteFile.delete();
				}
			}
		}
	}
	public void delImg2() {
		if(!fileName.equals("sundth.PNG"))
		{
		System.out.println("deleteeeeeeeeeee2 " +fileName);
		ExternalContext extContext = FacesContext.getCurrentInstance().getExternalContext();
		File deleteFile = new File(extContext.getRealPath("//images//" + fileName)); 
        deleteFile.delete();
		}
	}
}
